package cn.school.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
//@WebServlet("/HelloServlet")
@WebServlet("/wenhou/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public HelloServlet() {
		System.out.println("HelloServlet加载并实例化");
	}

	private String coding;

	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		// 获得初始化参数
		coding = config.getInitParameter("zifuji");
		System.out.println("获得初始化参数:" + coding);
		System.out.println("hello servlet完成了初始化");
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
		System.out.println("hello servlet销毁了");
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("进入了服务方法!!!");
		super.service(req, resp);
//		String method = req.getMethod();//
//		if (method.equalsIgnoreCase("get")) {
//			doGet(req, resp);
//		} else if (method.equalsIgnoreCase("post")) {
//			doPost(req, resp);
//		}
	}

	// 大部分情况,doGet和doPost行为一致
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// request.getContextPath()
		request.getRequestDispatcher("/nihao.jsp").forward(request, response);
		;

//		response.setContentType("text/html; charset=" + coding);
//		// 上一行一定要在获得out之前
//		PrintWriter out = response.getWriter();
//		out.append("Served at: ").append(request.getContextPath() + "<br/>");
//		out.append("你好,This is a servlet,this is a get method");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String u = request.getParameter("userName");
		String p = request.getParameter("userpass");
		PrintWriter out = response.getWriter();
		out.append("Served at: ").append(request.getContextPath() + "<br/>");
		out.append("Hello,This is a servlet,this is a post method");
		out.append("您输入的是" + u + "," + p);
	}

}
